const express = require('express')
const router = express.Router()
const humps = require('humps')
const svgCaptcha = require('svg-captcha')
const db = require('../../database/db')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const settings = require('../../../config/settings')
let captchaText = ''
module.exports = (() => {
    // 用户角色权限
    router.post('/login', async (req, res, next) => {
        try {
            if (captchaText !== req.body.captcha) {
                return res.json({
                    status: 404,
                    msg: '验证码错误！'
                })
            }
            const account = req.body.account
            const password = req.body.password
            const exisUser = await db.getUserByAccount(account)
            if (!exisUser) {
                return res.json({
                    status: 404,
                    msg: '账户不存在'
                })
            }

            const token = jwt.sign({ account: req.body.account }, settings.token_secret_key, {
                expiresIn: 7200,
            })
            bcrypt.compare(password, exisUser.password, (err, res) => {
                tryLogin(err, res)
            })
            const tryLogin = async (err, pwdMatchFlag) => {
                if (err) {
                    return res.json({
                        status: 0,
                        msg: '密码错误'
                    })
                }
                const loginUser = await db.getLoginUser(req.body.account)
                const rels = await db.getRoleActionByRoleId(loginUser.role_id)
                const temp = []
                const promises = []
                loginUser.actions = []
                rels.forEach(rel => {
                    const promise = new Promise(async resolve => {
                        temp.push(await db.getActionById(rel.action_id))
                        resolve(temp)
                    })
                    promises.push(promise)
                })
                Promise.all(promises).then(() => {
                    temp.forEach(async item => {
                        loginUser.actions.push(item[0].alias)
                    })
                }).then(() => {
                    res.json({
                        status: 1,
                        msg: 'ok',
                        token: token,
                        user: loginUser
                    })
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/captcha', (req, res) => {
        svgCaptcha.options.width = 80
        svgCaptcha.options.height = 33
        svgCaptcha.options.fontSize = 40
        const captcha = svgCaptcha.create()
        captchaText = captcha.text
        res.send(captcha.data)
    })

    router.put('/resetPassword/:id', async (req, res, next) => {
        try {
            let exisUser = await db.getUserById(req.params.id)
            if (!exisUser) {
                return res.json({
                    status: 0,
                    msg: '账户不存在'
                })
            }

            bcrypt.compare(req.body.originalPassword, exisUser.password, (err, res) => {

                tryLogin(res)
            }); // 判断原密码是否正确
            tryLogin = async (pwdMatchFlag) => {
                if (!pwdMatchFlag) {
                    return res.json({
                        status: 0,
                        msg: '请输入正确原密码！'
                    })
                }

                exisUser.password = await bcrypt.hash(req.body.newPassword, 12)
                const success = await db.updatePassword(req.params.id, exisUser) // 更新密码

                if (!success) {
                    return res.json({
                        status: 0,
                        msg: '错误！'
                    })
                }

                res.json({
                    status: 1,
                    msg: 'ok',
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/users', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getUsers())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.get('/roles', async (req, res, next) => {
        try {
            const doc = await db.getRoles()
            doc.forEach((item) => {
                item.action_name = item.action_name.split(",")
            })
            res.send(humps.camelizeKeys(doc))
        } catch (err) {
            next(err)
        }
    })

    router.get('/roleList', async (req, res, next) => {
        try {
            const doc = await db.getRoleList()
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.get('/actions', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getActions())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addUser', async (req, res, next) => {
        try {
            let existUser = await db.getUserByAccount(req.body.account)

            if (existUser) {
                return res.json({
                    status: 0,
                    msg: '用户已存在！'
                })
            }

            req.body.password = await bcrypt.hash(req.body.password, 12)
            db.addUser(req.body).then(async (data) => {
                const role = await db.getRoleByAlias(req.body.role)
                const success = await db.addUserRoleRel({ user_id: data.insertId, role_id: role.id })
                if (success) {
                    res.json({
                        status: 1,
                        msg: 'ok'
                    })
                }
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/addRole', async (req, res, next) => {
        try {
            let existRole = await db.getRoleByName(req.body.name)
            if (existRole) {
                return res.json({
                    status: 0,
                    msg: '角色已存在！'
                })
            }

            db.addRole(req.body).then(async (data) => {
                const temp = []
                const promises = []
                req.body.actions.forEach(item => {
                    const promise = new Promise(async resolve => {
                        temp.push(await db.getActionByAlias(item))
                        resolve(temp)
                    })
                    promises.push(promise)
                })
                Promise.all(promises).then(() => {
                    temp.forEach(async item => {
                        await db.addRoleActionRel({ role_id: data.insertId, action_id: item.id })
                    })
                }).then(() => {
                    res.json({
                        status: 1,
                        msg: 'ok'
                    });
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeRole/:id', async (req, res, next) => {
        try {
            let existRole = await db.getRoleById(req.params.id)
            if (!existRole) {
                return res.json({
                    status: 0,
                    msg: '角色不存在！'
                })
            }

            await db.rmRoleActionRel(req.params.id) // 先获取关联表数据
            db.rmRoleById(req.params.id).then(async () => { // 先删除角色，再判断有没有用户，如果有用户就删除用户和用户角色关联表
                const rel = await db.getUserRoleRel(req.params.id) // 先获取关联表数据
                if (rel.length) { // 如果有关联表数据就根据数据删除用户
                    new Promise(resolve => {
                        resolve(
                            rel.forEach(async item => {
                                await db.rmUserById(item.user_id) // 删除角色
                                await db.rmUserRoleRel(item.user_id) // 删除用户角色关联表数据
                            }))
                    }).then(() => {
                        res.json({
                            status: 1,
                            msg: 'ok'
                        })
                    })
                } else {
                    res.json({
                        status: 1,
                        msg: 'ok'
                    })
                }
            })
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeUser/:id', async (req, res, next) => {
        try {
            let existUser = await db.getUserById(req.params.id)
            if (!existUser) {
                return res.json({
                    status: 0,
                    msg: '用户不存在！'
                })
            }

            db.rmUserById(req.params.id).then(async () => {
                const success = await db.rmUserRoleRel(req.params.id) // 删除用户角色关联表数据

                if (success) {
                    res.json({
                        status: 1,
                        msg: 'ok'
                    })
                }
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editRole/:id', async (req, res, next) => {
        try {
            let existRole = await db.getRoleById(req.params.id)
            if (!existRole) {
                return res.json({
                    status: 0,
                    msg: '角色不存在！'
                })
            }

            db.rmRoleActionRel(req.params.id).then(() => {
                const temp = []
                const promises = []
                req.body.actions.forEach(item => {
                    const promise = new Promise(async resolve => {
                        temp.push(await db.getActionByAlias(item))
                        resolve(temp)
                    })
                    promises.push(promise)
                })
                Promise.all(promises).then((data) => {
                    temp.forEach(async item => {
                        await db.addRoleActionRel({ role_id: req.params.id, action_id: item.id })
                    })
                }).then(async () => {
                    const success = await db.updateRole(req.params.id, req.body)

                    if (success) {
                        res.json({
                            status: 1,
                            msg: 'ok'
                        })
                    }
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editUser/:id', async (req, res, next) => {
        try {
            let existUser = await db.getUserById(req.params.id)
            if (!existUser) {
                return res.json({
                    status: 0,
                    msg: '用户不存在！'
                })
            }

            if (req.body.password) { // 有密码
                req.body.password = await bcrypt.hash(req.body.password, 12)
                await db.resetUserPassword(req.params.id, req.body.password)
            }

            await db.updateUser(req.params.id, req.body) // 更新用户表数据
            db.rmUserRoleRel(req.params.id).then(async () => { // 删除用户角色关联表数据
                const role = await db.getRoleByAlias(req.body.role)
                db.addUserRoleRel({ user_id: req.params.id, role_id: role.id }).then(() => {
                    res.json({
                        status: 1,
                        msg: 'ok'
                    })
                })
            })
        } catch (err) {
            next(err)
        }
    })

    return router
})();